//
//  ViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/15.
//

import UIKit
import YYText
import SnapKit
import Alamofire
import SwiftyJSON
import Toast_Swift
import MJRefresh
import Foundation
import LGAlertView

class MBDMainViewController: MBDBaseViewController {
    var tableView : UITableView!
    var searchBar : UISearchBar!
    
    var viewModel : MBDMainViewModel!
    var pageIndex : Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = MBDMainViewModel()
        pageIndex = 1
        
        //防止push过程中的黑边
        self.navigationController?.view.backgroundColor = UIColor.white
        
        let rightItem = UIButton(frame: CGRectMake(0, 0, 45, 25))
        rightItem.setImage(UIImage(named: "ico_plus"), for: .normal)
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        
        //高度默认就是 42，设置成其他高度也不生效
        searchBar = UISearchBar(frame: CGRectMake(0, 3, UIScreen.main.bounds.width - 120, 21))
        if #available(iOS 13.0, *) {
            searchBar.searchTextField.font = UIFont.systemFont(ofSize: 14)
            searchBar.searchTextField.layer.cornerRadius = 21 // I've tried other numbers besides this too with no luck
            
            searchBar.searchTextField.clipsToBounds = true

        } else {
            // Fallback on earlier versions
        }
                
        searchBar.setDynamicSearchBarBackgroundColor()
        searchBar.delegate = self
        //左边的 icon 往右边动一动
        searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
        
        self.navigationItem.titleView = searchBar
        
        tableView = UITableView()
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [unowned self] in
            self.pageIndex = 1
            self.tableView.mj_footer?.resetNoMoreData()

            self.viewModel.doRequest { (error,result,totalPage) in
                self.viewModel.cellModels = result
                
                self.tableView.reloadData()
                
                self.tableView.mj_header?.endRefreshing()
                if self.pageIndex >= totalPage {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.tableView.mj_footer?.resetNoMoreData()
                }
            }
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            [unowned self] in
            
            self.pageIndex += 1
            self.viewModel.doRequest(pageNum: pageIndex, completion: { (error,result,totalPage) in
                
                var groups = Array<MBDMainCellModel>()
                groups.append(contentsOf: self.viewModel.cellModels ?? Array<MBDMainCellModel>())
                
                if result?.count ?? 0 > 0 {
                    groups.append(contentsOf: result!)
                }
                
                self.viewModel.cellModels = groups
                
                self.tableView.reloadData()

                self.tableView.mj_footer?.endRefreshing()
                
                if self.pageIndex >= totalPage {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }

            })
        })
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self

        tableView.register(MBDGroupMainCell.self, forCellReuseIdentifier: "MBDGroupMainCell")
        
        tableView.setDynamicBackgroundColor()
        searchBar.setDynamicSearchBarBackgroundColor()
        self.refreshUI()
    }    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func refreshUI(){
        self.pageIndex = 1
        self.viewModel.doRequest { (error,result,totalPage) in
            
            if (result?.count ?? 0) > 0 {
                self.viewModel.cellModels = result
                
                self.tableView.reloadData()
                
                self.tableView.restore()
            } else {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                
                self.tableView.setEmptyView(title: "数据为空，可能出了点问题",message: "")
            }
            
            //如果只有一页，那就不要展示更多按钮展示
            if totalPage == 1 {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.resetNoMoreData()
            }
            
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        searchBar.resignFirstResponder()

        super.viewWillDisappear(animated)
    }
        
    @objc func rightItemPressed(){
        let vc = MBDUploadGroupViewController(viewModel: MBDUploadGroupViewModel())
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if traitCollection.userInterfaceStyle == .dark {
            return .lightContent  // 暗黑模式下，状态栏文字为白色
        } else {
            if #available(iOS 13.0, *) {
                return .darkContent
            } else {
                // Fallback on earlier versions
                return .default
            }   // 浅色模式下，状态栏文字为黑色 (iOS 13 及之后)
            
        }
    }

    
    override var prefersStatusBarHidden: Bool {
        return false
    }
    
    
    override func updateColors() {
        tableView.setDynamicBackgroundColor()
        searchBar.setDynamicSearchBarBackgroundColor()
        
        // 遍历并更新 cellModels
        if let cellModels = self.viewModel.cellModels {
            for i in 0..<cellModels.count {
                let updatedGroupDetail = cellModels[i].groupDetail
                
                // 重新设置 groupDetail
                self.viewModel.cellModels?[i].groupDetail = updatedGroupDetail
            }
        }
        
        self.tableView.reloadData()
    }
}

extension MBDMainViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupMainCell", for: indexPath)
        let cellModel = self.viewModel.cellModels![indexPath.row]
        (cell as! MBDGroupMainCell).cellModel = cellModel
        return cell
    }
}


extension MBDMainViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let detail = MBDGroupDetailViewModel(groupDetail: cellModel.groupDetail)
        let vc = MBDGroupDetailViewController(viewModel: detail)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.searchBar.resignFirstResponder()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let groupCellModel = self.viewModel.cellModels![indexPath.row]

        return groupCellModel.cellHeight
    }
}

extension MBDMainViewController: UISearchBarDelegate {
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        
    }
    
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {

        let vc = MBDGroupSearchViewController()
        self.navigationController?.pushViewController(vc, animated: true)

        return true
    }
}

